﻿using JESAI.DynamicWebApi.Attributes;
using JESAI.DynamicWebApi.Configurations;
using JESAI.DynamicWebApi.Extensions;
using JESAI.DynamicWebApi.Helpers;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Mvc.ActionConstraints;
using Panda.DynamicWebApi.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace JESAI.DynamicWebApi.Conventions
{
    /// <summary>
    /// 动态WebApi协议
    /// 重写默认的ApplicationModelConvention
    /// </summary>
    public class DynamicWebApiAppServiceConvention: IApplicationModelConvention
    {
        /// <summary>
        /// 延迟动态WebApi配置文件的对象加载，使得第一次使用才被创建
        /// </summary>
        private readonly Lazy<IDynamicWebApiConfiguration> _configuration;

        public DynamicWebApiAppServiceConvention(IServiceCollection services)
        {
            //得到注入的配置文件
            _configuration = new Lazy<IDynamicWebApiConfiguration>(() =>
            {             
                return services.GetSingletonInstanceOrNull<IDynamicWebApiConfiguration>();
            }, true);
        }
        /// <summary>
        /// 实现IApplicationModelConvention的Apply方法。
        /// </summary>
        /// <param name="application"></param>
        public void Apply(ApplicationModel application)
        {
            foreach (var controller in application.Controllers)
            {
                var type = controller.ControllerType.AsType();
                var configuration = GetControllerSettingOrNull(type);

                //确定是否可以将指定类型的实例分配给变量
                if (typeof(IDynamicWebApiService).GetTypeInfo().IsAssignableFrom(type))
                {
                    //移除给定后缀，如AsyncCrudAppService。则控制器名称为AsyncCurd
                    controller.ControllerName = controller.ControllerName.RemovePostFix(AppConsts.ControllerPostfixes);

                    configuration?.ControllerModelConfigurer(controller);

                    ConfigureArea(controller, configuration);
                    ConfigureDynamicWebApiService(controller, configuration);
                }
                else
                {
                    var dynmicWebApiAttr = ReflectionHelper.GetSingleAttributeOrDefault<DynamicWebApiAttribute>(type.GetTypeInfo());
                    if (dynmicWebApiAttr != null && dynmicWebApiAttr.IsEnabledFor(type))
                    {
                        ConfigureDynamicWebApiService(controller, configuration);
                    }
                }
            }
        }
        /// <summary>
        /// 配置Area区域，即把模块名称添加到路由里面去
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="configuration"></param>
        private void ConfigureArea(ControllerModel controller, [CanBeNull] DynamicWebApiControllerAssemblySetting configuration)
        {
            if (configuration == null)
            {
                return;
            }

            if (controller.RouteValues.ContainsKey("area"))
            {
                return;
            }

            controller.RouteValues["area"] = configuration.ModuleName;
        }

        /// <summary>
        /// 配置动态WebApi服务
        /// </summary>
        /// <param name="controller">控制器模型</param>
        /// <param name="configuration">控制器程序集配置信息</param>
        private void ConfigureDynamicWebApiService(ControllerModel controller, [CanBeNull] DynamicWebApiControllerAssemblySetting configuration)
        {
            ConfigureApiExplorer(controller);
            ConfigureSelector(controller, configuration);
            ConfigureParameters(controller);
        }

        /// <summary>
        /// 配置参数
        /// </summary>
        /// <param name="controller">控制器模型</param>
        private void ConfigureParameters(ControllerModel controller)
        {
            foreach (var action in controller.Actions)
            {
                foreach (var prm in action.Parameters)
                {
                    if (prm.BindingInfo != null)
                    {
                        continue;
                    }

                    //如果参数不是基本类型
                    if (!TypeHelper.IsPrimitiveExtendedIncludingNullable(prm.ParameterInfo.ParameterType))
                    {
                        //判断参数是否能绑定到FormBody
                        if (CanUseFormBodyBinding(action, prm))
                        {
                            prm.BindingInfo = BindingInfo.GetBindingInfo(new[] { new FromBodyAttribute() });
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 判断参数是否可以用FormBody来绑定
        /// </summary>
        /// <param name="action">action模型</param>
        /// <param name="parameter">参数模型</param>
        /// <returns></returns>
        private bool CanUseFormBodyBinding(ActionModel action, ParameterModel parameter)
        {
            //如果存在配置的忽略binding类型，则返回false
            if (_configuration.Value.FormBodyBindingIgnoredTypes.Any(t => t.IsAssignableFrom(parameter.ParameterInfo.ParameterType)))
            {
                return false;
            }

            foreach (var selector in action.Selectors)
            {
                if (selector.ActionConstraints == null)
                {
                    continue;
                }

                foreach (var actionConstraint in selector.ActionConstraints)
                {
                    var httpMethodActionConstraint = actionConstraint as HttpMethodActionConstraint;
                    if (httpMethodActionConstraint == null)
                    {
                        continue;
                    }

                    if (httpMethodActionConstraint.HttpMethods.All(hm => hm.IsIn("GET", "DELETE", "TRACE", "HEAD")))
                    {
                        return false;
                    }
                }
            }

            return true;
        }

        /// <summary>
        /// 配置控制器的API浏览器
        /// </summary>
        /// <param name="controller">控制器模型</param>
        private void ConfigureApiExplorer(ControllerModel controller)
        {
            //如果分组名称是空的，则用控制器分组
            if (controller.ApiExplorer.GroupName.IsNullOrEmpty())
            {
                controller.ApiExplorer.GroupName = controller.ControllerName;
            }

            //如果IsVisible是空，则获取当前控制器的DynamicWebApiAttribute，如果配置是True，则设置为可见，如果没有该特性，则默认是可见的。
            if (controller.ApiExplorer.IsVisible == null)
            {
                var controllerType = controller.ControllerType.AsType();
                var dynamicWebApiAttr = ReflectionHelper.GetSingleAttributeOrDefault<DynamicWebApiAttribute>(controllerType.GetTypeInfo());
                if (dynamicWebApiAttr != null)
                {
                    controller.ApiExplorer.IsVisible =
                        dynamicWebApiAttr.IsEnabledFor(controllerType) &&
                        dynamicWebApiAttr.IsMetadataEnabledFor(controllerType);
                }
                else
                {
                    controller.ApiExplorer.IsVisible = true;
                }
            }

            foreach (var action in controller.Actions)
            {
                ConfigureApiExplorer(action);
            }
        }
       /// <summary>
       /// 配置Action的API浏览器。
       /// </summary>
       /// <param name="action">Action请求</param>
        private void ConfigureApiExplorer(ActionModel action)
        {
            //判断Action所在地方是否存在属性开启，开启则标记为可见
            if (action.ApiExplorer.IsVisible == null)
            {
                var dynamicWebApiAttr = ReflectionHelper.GetSingleAttributeOrDefault<DynamicWebApiAttribute>(action.ActionMethod);
                if (dynamicWebApiAttr != null)
                {
                    action.ApiExplorer.IsVisible =
                        dynamicWebApiAttr.IsEnabledFor(action.ActionMethod) &&
                        dynamicWebApiAttr.IsMetadataEnabledFor(action.ActionMethod);
                }
            }
        }

        /// <summary>
        /// 配置Selector
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="configuration"></param>
        private void ConfigureSelector(ControllerModel controller, [CanBeNull] DynamicWebApiControllerAssemblySetting configuration)
        {
            RemoveEmptySelectors(controller.Selectors);

            //如果该控制器存在其中一个Selector，则不配置
            if (controller.Selectors.Any(selector => selector.AttributeRouteModel != null))
            {
                return;
            }

            var moduleName = GetModuleNameOrDefault(controller.ControllerType.AsType());

            foreach (var action in controller.Actions)
            {
                ConfigureSelector(moduleName, controller.ControllerName, action, configuration);
            }
        }
        /// <summary>
        /// 配置Selector
        /// </summary>
        /// <param name="moduleName"></param>
        /// <param name="controllerName"></param>
        /// <param name="action"></param>
        /// <param name="configuration"></param>
        private void ConfigureSelector(string moduleName, string controllerName, ActionModel action, [CanBeNull] DynamicWebApiControllerAssemblySetting configuration)
        {
            RemoveEmptySelectors(action.Selectors);

            //从Action方法上面获取DynamicWebApiAttribute
            var dynamicWebApiAttr = ReflectionHelper.GetSingleAttributeOrDefault<DynamicWebApiAttribute>(action.ActionMethod);
            //如果不启用动态WebApi功能，直接返回
            if (dynamicWebApiAttr != null && !dynamicWebApiAttr.IsEnabledFor(action.ActionMethod))
            {
                return;
            }
            //Selectors为空,则增加。如果不为空，则替换
            if (!action.Selectors.Any())
            {
                AddDynamicWebApiServiceSelector(moduleName, controllerName, action, configuration);
            }
            else
            {
                NormalizeSelectorRoutes(moduleName, controllerName, action);
            }
        }

        /// <summary>
        /// 直接new一个SelectModel，然后添加到Selectors里面去
        /// </summary>
        /// <param name="moduleName">模块名称</param>
        /// <param name="controllerName">控制器名称</param>
        /// <param name="action">ActionModel</param>
        /// <param name="configuration">程序集配置信息</param>
        private void AddDynamicWebApiServiceSelector(string moduleName, string controllerName, ActionModel action, [CanBeNull] DynamicWebApiControllerAssemblySetting configuration)
        {

            string verb;
            //获取ActionName的第一个单词，并转换为小写。
            var verbKey = action.ActionName.GetPascalOrCamelCaseFirstWord().ToLower();
            //根据不是标准的REST http谓词，转换为标准REST。如果不存在，则取默认的谓词
            verb = AppConsts.HttpVerbs.ContainsKey(verbKey) ? AppConsts.HttpVerbs[verbKey] : AppConsts.DefaultHttpVerb;

            action.ActionName = GetRestFulActionName(action.ActionName);
            var dynamicWebApiServiceSelectorModel = new SelectorModel
            {
                AttributeRouteModel = CreateDynamicWebApiServiceAttributeRouteModel(moduleName, controllerName, action)
            };

  

            dynamicWebApiServiceSelectorModel.ActionConstraints.Add(new HttpMethodActionConstraint(new string[] { verb }));

            action.Selectors.Add(dynamicWebApiServiceSelectorModel);
        }
        /// <summary>
        /// 获取Rest风格的Action名称
        /// </summary>
        /// <param name="actionName">Action名称</param>
        /// <returns>字符串</returns>
        private static string GetRestFulActionName(string actionName)
        {
            // 比如AddNameAppllicationService，移除后缀变成AddName
            // Remove Postfix
            actionName = actionName.RemovePostFix(AppConsts.ActionPostfixes.ToArray());
            //比如 AsyncAddModel 。
            //移除前缀变成AddModel
            // Remove Prefix
            var verbKey = actionName.GetPascalOrCamelCaseFirstWord().ToLower();
            if (AppConsts.HttpVerbs.ContainsKey(verbKey))
            {
                if (actionName.Length == verbKey.Length)
                {
                    return actionName;
                }
                else
                {
                    return actionName.Substring(verbKey.Length);
                }
            }
            else
            {
                return actionName;
            }
        }
        /// <summary>
        /// 循环所有selector，如果selector不存在路由特性，则创建一个路由替换
        /// </summary>
        /// <param name="moduleName">模块名称</param>
        /// <param name="controllerName">控制器名称</param>
        /// <param name="action">ActionModel</param>
        private static void NormalizeSelectorRoutes(string moduleName, string controllerName, ActionModel action)
        {
            foreach (var selector in action.Selectors)
            {
                if (selector.AttributeRouteModel == null)
                {
                    selector.AttributeRouteModel = CreateDynamicWebApiServiceAttributeRouteModel(
                        moduleName,
                        controllerName,
                        action
                    );
                }
            }
        }

        /// <summary>
        /// 获取控制器的模块名称或者拿默认的模块名称
        /// </summary>
        /// <param name="controllerType">控制器的Type类型</param>
        /// <returns></returns>
        private string GetModuleNameOrDefault(Type controllerType)
        {
            return GetControllerSettingOrNull(controllerType)?.ModuleName ??
                   AppConsts.DefaultServiceModuleName;
        }

        /// <summary>
        /// 获取指定控制器类型的配置信息
        /// </summary>
        /// <param name="controllerType">控制器类型</param>
        /// <returns></returns>
        [CanBeNull]
        private DynamicWebApiControllerAssemblySetting GetControllerSettingOrNull(Type controllerType)
        {
            var settings = _configuration.Value.dynamicWebApiControllerAssemblySettings.GetSettings(controllerType);
            return settings.FirstOrDefault(setting => setting.TypePredicate(controllerType));
        }

        /// <summary>
        /// 创建一个新的路由特性
        /// </summary>
        /// <param name="moduleName">模块名称</param>
        /// <param name="controllerName">控制器名称</param>
        /// <param name="action">Action模型</param>
        /// <returns>路由特性模型实例</returns>
        private static AttributeRouteModel CreateDynamicWebApiServiceAttributeRouteModel(string moduleName, string controllerName, ActionModel action)
        {
            return new AttributeRouteModel(
                new RouteAttribute(
                    $"api/services/{moduleName}/{controllerName}/{action.ActionName}"
                )
            );
        }

        /// <summary>
        /// 移除同时没有在设置路由特性（AttributeRoute）和Action的选择器
        /// </summary>
        /// <param name="selectors">选择器集合</param>
        private static void RemoveEmptySelectors(IList<SelectorModel> selectors)
        {
            selectors
                .Where(IsEmptySelector)
                .ToList()
                .ForEach(s => selectors.Remove(s));
        }

        /// <summary>
        /// 判断选择器模型的路由特性模型和Action是否为空
        /// </summary>
        /// <param name="selector">选择器模型实例</param>
        /// <returns>布尔值</returns>
        private static bool IsEmptySelector(SelectorModel selector)
        {
            return selector.AttributeRouteModel == null && selector.ActionConstraints.IsNullOrEmpty();
        }
    }
}
